

from PIL import Image, ImageDraw

def split_image(image_path, num_rows, num_cols):
    img = Image.open(image_path)
    img_width, img_height = img.size
    cell_width = img_width // num_cols
    cell_height = img_height // num_rows

    colors = []
    for row in range(num_rows):
        for col in range(num_cols):
            center_x = (col * cell_width) + (cell_width // 2)
            center_y = (row * cell_height) + (cell_height // 2)
            color = img.getpixel((center_x, center_y))
            colors.append(color)

    return colors, cell_width, cell_height

def draw_image(colors, num_rows, num_cols, cell_width, cell_height):
    img_width = num_cols * cell_width
    img_height = num_rows * cell_height
    img = Image.new("RGB", (img_width, img_height))
    draw = ImageDraw.Draw(img)

    for row in range(num_rows):
        for col in range(num_cols):
            index = (row * num_cols) + col
            x0 = col * cell_width
            y0 = row * cell_height
            x1 = x0 + cell_width
            y1 = y0 + cell_height
            draw.rectangle([(x0, y0), (x1, y1)], fill=colors[index])
            draw.text((x0 + 5, y0 + 5), f"{colors[index]}", fill=(255, 255, 255))

    return img

# 示例用法
image_path = "lametric_image.png"
num_rows = 10
num_cols = 10

colors, cell_width, cell_height = split_image(image_path, num_rows, num_cols)
img = draw_image(colors, num_rows, num_cols, cell_width, cell_height)
img.save("lametric_image_1.png")
